package com.cloudkinto.service.order.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.order.OrderYahooQueryBo;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.XmlUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.finance.vo.IdAndNameEntity;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.order.OrderYahooService;
import com.cloudkinto.service.order.vo.OrderYahooExcelExportVo;
import com.cloudkinto.service.order.vo.OrderYahooItemExcelExportVo;
import com.cloudkinto.service.order.vo.yahoo.*;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputPackageAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.product.ProductCombinationService;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.user.UserService;
import com.cloudkinto.utils.YahooUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.jdom2.JDOMException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author huajiyu
 * @since 2022-07-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class OrderYahooServiceImpl extends ServiceImpl<OrderYahooDao, OrderYahooDo> implements OrderYahooService {
    @Autowired
    private OrderYahooDao dao;
    // @Autowired
    // private RedisTemplate redisTemplate;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //    @Autowired
    // private ShopService shopService;
    @Autowired
    private UserService userService;
    //    @Autowired
    private OperateRecordDao operateRecordDao;
    @Autowired
    private OrderOutputService orderOutputService;
    //    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private CompanyAccountService mAccountService;
    @Autowired
    private OrderYahooItemDao itemDao;
    @Autowired
    private ShipPriceService shipPriceService;
    @Autowired
    private JpRegionService mRegionService;
    @Autowired
    private StockRecordDao stockDao;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private ProductCombinationService productCombinationService;
    @Autowired
    private OperateRecordService operateRecordService;
    @Autowired
    private StockRecordService stockRecordService;


    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        OrderYahooDo entityDo = new OrderYahooDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderYahooDo entityDo, Long userId) {

    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OrderYahooDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*OrderYahooDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OrderYahooDo entityDo, Long userId) {

    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(OrderYahooDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        OrderYahooDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderYahooDo entityDo, Long userId) {

    }

    @Override
    public OrderYahooDetailRes detail(Long id) {
        OrderYahooDo entityDo = dao.selectById(id);
        return handlerDetailAfter(entityDo);
    }

    //查询明细之后要执行的业务定制处理
    private OrderYahooDetailRes handlerDetailAfter(OrderYahooDo entityDo) {
        OrderYahooDetailRes res = new OrderYahooDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        ShopDo shopDo = shopDao.selectById(entityDo.getShopId());
        if (shopDo != null) res.setShopName(shopDo.getShopName());
        res.setSettleStatus(getSettleStatus(entityDo.getSettleStatus()));
        res.setShipName(entityDo.getShipFirstName() + " " + entityDo.getShipLastName());
        LambdaQueryWrapper<OrderYahooItemDo> itemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        itemDoLambdaQueryWrapper.eq(OrderYahooItemDo::getOrderId, entityDo.getId());
        List<OrderYahooItemDo> itemDoList = itemDao.selectList(itemDoLambdaQueryWrapper);
        for (OrderYahooItemDo orderYahooItemDo : itemDoList) {
            OrderYahooItemDetail detail = new OrderYahooItemDetail();
            detail.setQuantity(orderYahooItemDo.getQuantity());
            detail.setItemId(StringUtils.isNotBlank(orderYahooItemDo.getSubCode()) ? orderYahooItemDo.getSubCode() : orderYahooItemDo.getItemId());
            detail.setTitle(orderYahooItemDo.getTitle());
            if (res.getItem() == null) res.setItem(new ArrayList<>());
            res.getItem().add(detail);
        }
        List<OperateRes> operateRecordDos = operateRecordService.getOperateList(res.getId(), 5);
        res.setOperateResList(operateRecordDos);
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<ShopDo> shopWrapper = new LambdaQueryWrapper<>();
        shopWrapper.eq(ShopDo::getCompanyId, companyId);
        List<ShopDo> shopDoList = shopDao.selectList(shopWrapper);
        List<IdAndNameEntity> collect = shopDoList.stream()
                .filter(shopDo -> shopDo.getYahooRefreshToken() != null)
                .map(shopDo -> new IdAndNameEntity(shopDo.getId().intValue(), shopDo.getShopName()))
                .collect(Collectors.toList());
        map.put("shopList", collect);
        return SingleResult.success(map);
    }

    @Override
    public List<OrderYahooDoPageEntity> getList(OrderYahooQueryBo bo) {
        LambdaQueryWrapper<OrderYahooDo> wrapper = queryBuild(bo);
        List<OrderYahooDo> list = this.list(wrapper);
        return handlerListAfter(list);
    }

    @Override
    public PageResult getListPage(OrderYahooQueryBo bo) {
        IPage<OrderYahooDo> page = new Page<>(bo.getCurrent(), bo.getPageSize());
        page = this.page(page, queryBuild(bo));
        List<OrderYahooDoPageEntity> resList = handlerListAfter(page.getRecords());
        return new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
    }

    //查询分页列表之后对列表数据的处理
    private List<OrderYahooDoPageEntity> handlerListAfter(List<OrderYahooDo> list) {
        List<OrderYahooDoPageEntity> result;
        result = list.stream().map(orderYahooDo -> {
            OrderYahooDoPageEntity orderYahooDoPage = new OrderYahooDoPageEntity();
            BeanUtils.copyProperties(orderYahooDo, orderYahooDoPage);
            ShopDo shopDo = shopDao.selectById(orderYahooDo.getShopId());
            if (shopDo != null) orderYahooDoPage.setShopName(shopDo.getShopName());
            if (StringUtils.isNotBlank(orderYahooDo.getPayKind()))
                orderYahooDoPage.setPayKind(getPayKind(orderYahooDo.getPayKind()));
            if (StringUtils.isNotBlank(orderYahooDo.getSettleStatus()))
                orderYahooDoPage.setSettleStatus(getSettleStatus(orderYahooDo.getSettleStatus()));
            orderYahooDoPage.setShipName(orderYahooDo.getShipLastName() + " " + orderYahooDo.getShipFirstName());
            LambdaQueryWrapper<OrderYahooItemDo> itemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            itemDoLambdaQueryWrapper.eq(OrderYahooItemDo::getOrderId, orderYahooDo.getId());
            List<OrderYahooItemDo> itemDoList = itemDao.selectList(itemDoLambdaQueryWrapper);
            String sku = itemDoList.stream().map(i -> StringUtils.isNotBlank(i.getSubCode()) ? i.getSubCode() : i.getItemId()).collect(Collectors.joining(","));
            orderYahooDoPage.setSku(sku);
            return orderYahooDoPage;
        }).collect(Collectors.toList());
        return result;
    }

    private String getSettleStatus(String settleStatus) {
        //1 : 決済申込
        //2 : 支払待ち
        //3 : 支払完了
        //4 : 入金待ち
        //5 : 決済完了
        //6 : キャンセル
        //7 : 返金
        //8 : 有効期限切れ
        //9 : 決済申込中
        //10 : オーソリエラー
        //11 : 売上取消
        //12 : Suicaアドレスエラー
        switch (settleStatus) {
            case "1":
                return "決済申込";
            case "2":
                return "支払待ち";
            case "3":
                return "支払完了";
            case "4":
                return "入金待ち";
            case "5":
                return "決済完了";
            case "6":
                return "キャンセル";
            case "7":
                return "返金";
            case "8":
                return "有効期限切れ";
            case "9":
                return "決済申込中";
            case "10":
                return "オーソリエラー";
            case "11":
                return "売上取消";
            case "12":
                return "Suicaアドレスエラー";
        }
        return null;
    }

    private String getPayKind(String payKind) {
        //0 : カード
        //1 : ネットバンキング
        //2 : キャリア決済
        //3 : 振込
        //4 : 代引
        //5 : コンビニ
        //6 : 電子マネー
        //7 : その他
        switch (payKind) {
            case "0":
                return "カード";
            case "1":
                return "ネットバンキング";
            case "2":
                return "キャリア決済";
            case "3":
                return "振込";
            case "4":
                return "代引";
            case "5":
                return "コンビニ";
            case "6":
                return "電子マネー";
            case "7":
                return "その他";
        }
        return null;
    }

    private IPage<OrderYahooDo> pageInit(Map<String, String> map) {
        IPage<OrderYahooDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private LambdaQueryWrapper<OrderYahooDo> queryBuild(OrderYahooQueryBo bo) {
        LambdaQueryWrapper<OrderYahooDo> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getOrderId()), OrderYahooDo::getOrderId, bo.getOrderId());
        lqw.like(StringUtils.isNotBlank(bo.getShipFirstName()), OrderYahooDo::getShipFirstName, bo.getShipFirstName());
        lqw.like(StringUtils.isNotBlank(bo.getShipLastName()), OrderYahooDo::getShipLastName, bo.getShipLastName());
        lqw.like(StringUtils.isNotBlank(bo.getSystemMemo()), OrderYahooDo::getSystemMemo, bo.getSystemMemo());
        lqw.like(StringUtils.isNotBlank(bo.getShipPhone()), OrderYahooDo::getShipPhoneNumber, bo.getShipPhone());
        lqw.eq(Objects.nonNull(bo.getIsSend()), OrderYahooDo::getIsSendOut, bo.getIsSend());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderStatus()), OrderYahooDo::getOrderStatus, bo.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPayStatus()), OrderYahooDo::getPayStatus, bo.getPayStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getShipStatus()), OrderYahooDo::getShipStatus, bo.getShipStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getShopId()), OrderYahooDo::getShopId, bo.getShopId());
        lqw.eq(Objects.nonNull(bo.getCompanyId()), OrderYahooDo::getCompanyId, bo.getCompanyId());
        if ("0".equals(bo.getDateType())) {
            lqw.gt(Objects.nonNull(bo.getDateStart()), OrderYahooDo::getOrderTime, bo.getDateStart());
            lqw.le(Objects.nonNull(bo.getDateEnd()), OrderYahooDo::getOrderTime, bo.getDateEnd());
        } else {
            //更新时间
            lqw.gt(Objects.nonNull(bo.getDateStart()), OrderYahooDo::getLastUpdateTime, bo.getDateStart());
            lqw.le(Objects.nonNull(bo.getDateEnd()), OrderYahooDo::getLastUpdateTime, bo.getDateEnd());
        }
        lqw.orderByDesc(OrderYahooDo::getOrderTime);
        return lqw;
    }

    @Override
    public Map<String, Object> getYahooUserInfoApi(Long shopId) {
        String body = null;
        Map param = new HashMap<>();
//        param.put("callback", "success");//如果指定了 则以 Content-Type: text/javascript 形式返回响应。
        try {
            body = YahooUtils.yahooDoGet("https://userinfo.yahooapis.jp/yconnect/v2/attribute", userService.getYahooUserAccessToken(shopId), param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isBlank(body)) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo获取用户信息api 连接超时");
            return result;
        }
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (StringUtils.isNotBlank(jsonObject.getString("error_description"))) {
            result.put("code", "FAIL");
            result.put("msg", jsonObject.getString("error_description"));
            return result;
        } else {
            //获取成功 保存
            YahooUserInfo userInfo = JSONObject.parseObject(body, YahooUserInfo.class);
            ShopDo shopDo = shopDao.selectById(shopId);
            if (shopDo != null) {
//                shopDo.setYahooSellerId(userInfo.getSub());
                shopDao.updateById(shopDo);
            } else {
                log.error("Yahoo getYahooUserInfoApi api 没有对应店铺,店铺id: " + shopId);
            }
            result.put("code", "SUCCESS");
        }
        return result;
    }


    public String getYahooOrderListParam(int Result, int Start, Date OrderTimeFrom, Date OrderTimeTo, String orderId, String Field, String sellerId) {
        if (OrderTimeFrom == null || OrderTimeTo == null) {
            OrderTimeTo = TimeUtils.formatDateToDate(new Date(), "yyyy-MM-dd HH:mm:ss", "Asia/Tokyo");//乐天店铺转成日本时间
            OrderTimeFrom = DateUtils.passingDate(OrderTimeTo, -3);
        } else {
            OrderTimeTo = TimeUtils.formatDateToDate(OrderTimeTo, "yyyy-MM-dd HH:mm:ss", "Asia/Tokyo");
            OrderTimeFrom = TimeUtils.formatDateToDate(OrderTimeFrom, "yyyy-MM-dd HH:mm:ss", "Asia/Tokyo");
        }
        String from = DateUtils.dateFormatToString(OrderTimeFrom, "yyyy-MM-dd HH:mm:ss").replace(" ", "T");
        String to = DateUtils.dateFormatToString(OrderTimeTo, "yyyy-MM-dd HH:mm:ss").replace(" ", "T");

        StringBuilder builder = new StringBuilder("<Req><Search><Result>");
        builder.append(Result).append("</Result><Start>").append(Start).append("</Start>").append("<Sort>+order_time</Sort>");
        builder.append("<Condition>");
        if (StringUtils.isBlank(orderId)) {
            builder.append("<OrderId>").append(orderId).append("</OrderId>");
        } else {
            builder.append("<OrderTimeFrom>").append(from).append("</OrderTimeFrom><OrderTimeTo>").append(to).append("</OrderTimeTo>");
        }
        builder.append("</Condition>").append("<Field>").append(Field).append("</Field></Search><SellerId>").append(sellerId).append("</SellerId></Req>");
        return builder.toString();
    }

    /**
     * 定时同步订单 发射器
     *
     * @param type
     */
    @Override
    public void timingSyncYahooOrder(String type) {
        List<ShopDo> list = shopDao.selectList(new LambdaQueryWrapper<ShopDo>().isNotNull(ShopDo::getYahooRefreshToken));

        for (ShopDo shopDo : list) {
            if (StringUtils.isBlank(shopDo.getYahooRefreshToken())) {//
                continue;
            }
            Map<String, String> map = new HashMap<>();
            map.put("shopName", shopDo.getShopName());
            map.put("type", type);
            map.put("shopId", shopDo.getId() + "");

            String end = TimeUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
            String before;
            if ("all".equals(type)) {
                //同步近7天的订单(创建时间)
                before = TimeUtils.formatDate(DateUtils.passingDate(new Date(), -7), "yyyy-MM-dd hh:mm:ss");
            } else {
                //日常更新 同步最近1 小时 的订单
                before = TimeUtils.formatDate(DateUtils.passingDateHour(new Date(), -1), "yyyy-MM-dd hh:mm:ss");
            }
            map.put("orderTimeTo", end);
            map.put("orderTimeFrom", before);
            getYahooOrderList(shopDo.getId(), map);
        }
    }

    @Override
    public List<Map> ordersyncInit(Long currentUserId, Long companyId) {
        List<Map> shopList = new ArrayList<>();
        UserDo userDo = userService.getById(currentUserId);
        if (userDo == null) throw new BizExceptionI18("no.user.info");
        LambdaQueryWrapper<ShopDo> shopWrapper = new LambdaQueryWrapper();
        if (userDo.getShopId() != null) shopWrapper.eq(ShopDo::getId, userDo.getShopId());
        shopWrapper.eq(ShopDo::getCompanyId, companyId);
        shopWrapper.isNotNull(ShopDo::getYahooRefreshToken);
        shopWrapper.isNotNull(ShopDo::getYahooSellerId);
        List<ShopDo> shopDoList = shopDao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map shopMap = new HashMap();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopList.add(shopMap);
            }
        }
        return shopList;
    }

    @Override
    public SingleResult queryOrder2SendOut(String[] orderids, Long currentUserId, boolean isAuto, Long companyId) {
        //校验余额是否不足
        mAccountService.sufficientFundsCheck(companyId);
        List<String> failOrders = new ArrayList<>();
        List<OrderOutputAddReq> resList = new ArrayList<>();
        for (String orderid : orderids) {
            List<OrderOutputAddReq> outputAddReqs = new ArrayList<>();
            try {
                outputAddReqs = sendOutOrder(orderid, currentUserId, isAuto);
            } catch (BizException e) {
                e.printStackTrace();
                failOrders.add(e.getMessage());
            }
            if (outputAddReqs.size() < 1) continue;
            resList.addAll(outputAddReqs);
//            Session session = mailService.initMailSession();
//            Transport transport = mailService.initMailTransport(session);
//             operateRecordService.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, Long.parseLong(orderid), currentUserId, 5);
//            operateRecord("点击发货", Long.parseLong(orderid), currentUserId);
        }
//        List<String> failOrders = new ArrayList<>();
        if (isAuto) {
            sendOutMatch(resList, currentUserId, companyId);
        }
        for (OrderOutputAddReq outputAddReq : resList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoService.getById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        Map map = new HashMap();
        map.put("orderList", resList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    private List<OrderOutputAddReq> sendOutOrder(String orderid, Long currentUserId, boolean isAuto) {
        List<OrderOutputAddReq> resList = new ArrayList<>();
        OrderYahooDo orderYahooDo = this.baseMapper.selectById(orderid);
        if (orderYahooDo == null) throw new BizExceptionI18(SysConstant.NO_ORDER_INFO_ID, orderYahooDo.getOrderId());
//        if (orderYahooDo == null) throw new BizException("该订单不存在" + orderYahooDo.getOrderId());
//        if ("1".equals(orderYahooDo.getOrderStatus()) || "2".equals(orderYahooDo.getOrderStatus()))
//            throw new BizException("该订单不在发货状态" + orderYahooDo.getOrderId());
        LambdaQueryWrapper<OrderYahooItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderYahooItemDo::getOrderId, orderid);
        List<OrderYahooItemDo> itemsDoList1 = itemDao.selectList(wrapper);
        List<OrderOutputProductAddReq> itemAddReqList = new ArrayList<>();

        //处理原产品信息   + ，组合产品情况
        for (OrderYahooItemDo productDo : itemsDoList1) {
            String itemId = StringUtils.isNotBlank(productDo.getSubCode()) ? productDo.getSubCode() : productDo.getItemId();
            if (itemId.contains("+")) {
                for (String sku : itemId.split("\\+")) {
                    OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                    Long productId = productInfoService.getProductId(sku, orderYahooDo.getCompanyId());
                    if (productId == null) {
                        throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), sku);
//                        throw new BizException(String.format("%s(未找到%s信息)", orderYahooDo.getOrderId(), sku));
                    }
                    productDo1.setProductId(productId);
                    productDo1.setCommoditySku(sku);
                    productDo1.setCount(productDo.getQuantity());
                    itemAddReqList.add(productDo1);
                }
            } else {
                ProductInfoDo productInfoDo = productInfoService.getProductDo(itemId, orderYahooDo.getCompanyId());
                if (productInfoDo == null) {
                    throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), itemId);
//                    throw new BizException(String.format("%s(未找到%s信息)", orderYahooDo.getOrderId(), productDo.getItemId()));
                }
                if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                    OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                    productDo1.setProductId(productInfoDo.getId());
                    productDo1.setCommoditySku(productInfoDo.getCommoditySku());
                    productDo1.setCount(productDo.getQuantity());
                    itemAddReqList.add(productDo1);
                } else {
                    LambdaQueryWrapper<ProductCombinationDo> productCombinationWrapper = new LambdaQueryWrapper<>();
                    productCombinationWrapper.eq(ProductCombinationDo::getParentId, productInfoDo.getId());
                    List<ProductCombinationDo> productCombinationDoList = productCombinationService.getBaseMapper().selectList(productCombinationWrapper);
                    for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                        if (productCombinationDo.getEffective() == 1) {
                            if (productCombinationDo.getEffectBeginTime() == null || productCombinationDo.getEffectEndTime() == null)
                                continue;
                            if (orderYahooDo.getOrderTime().getTime() < productCombinationDo.getEffectBeginTime().getTime()
                                    || orderYahooDo.getOrderTime().getTime() > productCombinationDo.getEffectEndTime().getTime())
                                continue;
                        }
                        OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                        ProductInfoDo productInfoDo1 = productInfoService.getById(productCombinationDo.getChildId());
                        if (productInfoDo1 == null) {
                            continue;
                        }
                        productDo1.setProductId(productCombinationDo.getChildId());
                        productDo1.setCommoditySku(productInfoDo1.getCommoditySku());
                        productDo1.setCount(productCombinationDo.getCount());
                        itemAddReqList.add(productDo1);
                    }
                }
            }
        }
        //订单
        OrderOutputAddReq res = new OrderOutputAddReq();
        if (orderYahooDo.getCompanyId() == 221) {
            if (orderYahooDo.getShipMethod().equals("postage5"))
                res.setTrackId(DicBusinessItemConstant.xinongExpress);
        }
//        if (StringUtils.isNotBlank(orderYahooDo.get()))
//            res.setCod((int) Double.parseDouble(orderYahooDo.getPaymentCod()));
        res.setSendDate(new Date());
        res.setPlatform("yahoo");
        res.setPlatformNumber(orderYahooDo.getId() + "");
        res.setShopId(orderYahooDo.getShopId());
        res.setCompanyId(orderYahooDo.getCompanyId());
        res.setOrderNo(orderYahooDo.getOrderId());
        res.setReceiverName(orderYahooDo.getShipLastName() + " " + orderYahooDo.getShipFirstName());
        res.setTelPhone(orderYahooDo.getShipPhoneNumber());
        res.setPostCode(orderYahooDo.getShipZipCode());
        res.setArea(orderYahooDo.getShipPrefecture());
        if (StringUtils.isNotBlank(orderYahooDo.getShipCity())) {
            res.setAddress(orderYahooDo.getShipCity() + getAddress(orderYahooDo.getShipAddress1(), orderYahooDo.getShipAddress2()));
        } else {
            res.setAddress(getAddress(orderYahooDo.getShipAddress1(), orderYahooDo.getShipAddress2()));
        }
        if (orderYahooDo.getShipRequestDate() != null) {
            res.setDeliveryDate(TimeUtils.formatDate(orderYahooDo.getShipRequestDate()));
        }
        if (orderYahooDo.getShipRequestTime() != null) {
            res.setDeliveryTime(orderYahooDo.getShipRequestTime().replaceAll(":00", ""));
        }
        long storageId = 0L;
        long stateId = 0;
        //item
        List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
        List<OrderOutputProductAddReq> failedItems = new ArrayList<>();
        if (!CollectionUtils.isEmpty(itemAddReqList)) {
            double[] size = new double[4];
            double shipPirce = 99999D;
            //先看都有货的仓库
            LambdaQueryWrapper<StorageDo> lambdaQueryWrapper1 = new LambdaQueryWrapper();
            lambdaQueryWrapper1.eq(StorageDo::getSupportShip, 1);
            List<StorageDo> firstStorages = storageDao.selectList(lambdaQueryWrapper1);
            kk:
            for (StorageDo storageDo : firstStorages) {
                for (OrderOutputProductAddReq itemsDo : itemAddReqList) {

                    Long productId = itemsDo.getProductId();
                    if (productId == null) {
                        throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), itemsDo.getCommoditySku());
//                        throw new BizException(String.format("%s(未找到%s信息)", orderYahooDo.getOrderId(), itemsDo.getCommoditySku()));
                    }
                    // LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                    // wrapper1.eq(StockRecordDo::getShopId, res.getShopId()).eq(StockRecordDo::getProductInfoId, productId).eq(StockRecordDo::getStorageId, storageDo.getId());
                    // StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                    // if (stockRecordDo == null) {
                    //     continue kk;
                    // }
                    // int
                    // noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageId) + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageId);

                    int count = itemsDo.getCount();
                    int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageId, productId, count);
                    if (canUseCount < count) {//优先仓库有库存，优先仓库发货
                        continue kk;
                    }
                }
                //
                storageId = storageDo.getId();
            }
            //默认仓库先捆包
            for (OrderOutputProductAddReq itemsDo : itemAddReqList) {
                Long productId = itemsDo.getProductId();
                if (productId == null) {
                    throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), itemsDo.getCommoditySku());
//                    throw new BizException(String.format("%s(未找到%s信息)", orderYahooDo.getOrderId(), itemsDo.getCommoditySku()));
                }
                stateId = mRegionService.getStateIdByPostCode(orderYahooDo.getShipZipCode());
                if (storageId != 0) {//大阪地区优先发货仓库
                } else if (stateId <= 8) {//大阪地区优先发货仓库
                    storageId = 12L;
                } else {//东京仓库优先发货仓库
                    storageId = 10L;
                }
                // LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                // wrapper1.eq(StockRecordDo::getShopId, res.getShopId()).eq(StockRecordDo::getProductInfoId, productId).eq(StockRecordDo::getStorageId, storageId);
                // StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                // if (stockRecordDo == null) {
                //     failedItems.add(itemsDo);
                //     continue;
                // }
                // int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageId) + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageId);
                int count = itemsDo.getCount();
                int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageId, productId, count);

                if (canUseCount < count) {//优先仓库有库存，优先仓库发货
                    failedItems.add(itemsDo);
                    continue;
                }
                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                productDetail.setOrderId(itemsDo.getOrderId());
                productDetail.setProductId(productId);
                productDetail.setCount(count);
                orderOutputProductDetailList.add(productDetail);
            }
            OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
            List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
            packageDetail.setProductList(orderOutputProductDetailList);
            OrderOutputAddReq addReq = new OrderOutputAddReq();
            BeanUtils.copyProperties(res, addReq);
            packageAddReqList.add(packageDetail);
            addReq.setStorageId(storageId);
            addReq.setPackageList(packageAddReqList);
            //默认仓库库存不足
            if (failedItems.size() != itemAddReqList.size() && storageId != 0) {
//            if (failedItems.size() < 1 && storageId != 0) {
                resList.add(addReq);
            } else {
                failedItems = itemAddReqList;
            } //一个仓库是否发完所有订单
            if (failedItems.size() > 0) {
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                //剩余一件商品无库存
                if (failedItems.size() == 1 && failedItems.get(0).getCount() == 1) {
                    storageId = 0L;
                    Long productId = failedItems.get(0).getProductId();
                    List<StorageDo> storageDos = storageDao.selectList(null);
                    int count = failedItems.get(0).getCount();
                    for (StorageDo storageDo : storageDos) {//遍历仓库是否都有库存
                        // LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                        // wrapper2.eq(StockRecordDo::getShopId, res.getShopId()).eq(StockRecordDo::getProductInfoId, productId).eq(StockRecordDo::getStorageId, storageDo.getId());
                        // StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                        size = shipPriceService.countSameSkuSize(new double[4], productId, count);
                        // int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId()) + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageDo.getId());
                        int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageDo.getId(), productId, count);

                        if (canUseCount >= count) {
                            List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(), size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                            if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                            if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                shipPirce = shipPriceDos.get(0).getPrice();
                                storageId = storageDo.getId();
                            }
                        }
                    }
                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                    productDetail.setProductId(productId);
                    productDetail.setCount(count);
                    productAddList.add(productDetail);
                    OrderOutputPackageAddReq packageDetail1 = new OrderOutputPackageAddReq();
                    if (storageId != 0) {
                        List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                        packageDetail1.setProductList(productAddList);
                        OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                        BeanUtils.copyProperties(res, addReq1);
                        packageAddReqList1.add(packageDetail1);
                        addReq1.setStorageId(storageId);
                        addReq1.setPackageList(packageAddReqList1);
                        resList.add(addReq1);
                    } else {
                        throw new BizExceptionI18(SysConstant.ORDER_NO_STOCK_ID, orderYahooDo.getOrderId(), failedItems.get(0).getCommoditySku());
//                        throw new BizException(String.format("%s(%s库存不足)", orderYahooDo.getOrderId(), failedItems.get(0).getCommoditySku()));
                    }
                } else {
                    List<OrderOutputProductAddReq> productAddList1 = new ArrayList<>();
                    //多件商品无库存，第二优先捆包
                    List<OrderOutputProductAddReq> productDoListFailed = new ArrayList<>();
                    List<OrderOutputProductAddReq> productDoListSuccess = new ArrayList<>();
                    LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper();
                    lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1).ne(StorageDo::getId, storageId);
                    if (stateId <= 8) {
                        lambdaQueryWrapper.orderByDesc(StorageDo::getStorageArea);
                    } else {
                        lambdaQueryWrapper.orderByAsc(StorageDo::getStorageArea);
                    }
                    List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
                    storageId = 0L;
                    if (storageDos != null) {
                        kk:
                        for (StorageDo storageDo : storageDos) {
                            ;//遍历支持捆包仓库是否都有库存
                            for (OrderOutputProductAddReq productDo : failedItems) {
                                Long productId = productDo.getProductId();
                                int count = productDo.getCount();
                                // LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                                // wrapper1.eq(StockRecordDo::getShopId, res.getShopId()).eq(StockRecordDo::getProductInfoId, productId).eq(StockRecordDo::getStorageId, storageDo.getId());
                                // StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                                // if (stockRecordDo == null) {
                                //     productDoListSuccess.clear();
                                //     productAddList1.clear();
                                //     productDoListFailed.clear();
                                //     productDoListFailed.addAll(failedItems);
                                //     continue kk;
                                // }
                                // int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId()) + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageDo.getId());
                                int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageDo.getId(), productId, count);

                                if (canUseCount < count) {
                                    productDoListSuccess.clear();
                                    productAddList1.clear();
                                    productDoListFailed.clear();
                                    productDoListFailed.addAll(failedItems);
                                    continue kk;
                                } else {
                                    productDoListSuccess.add(productDo);
                                }
                                if (storageId != 0 && storageId != storageDo.getId()) {
                                    productAddList1.clear();
                                    productDoListSuccess.clear();
                                    productDoListFailed.clear();
                                }
                                storageId = storageDo.getId();
                                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                productDetail.setProductId(productId);
                                productDetail.setCount(count);
                                productAddList1.add(productDetail);
                            }
                            if (productDoListSuccess.size() == failedItems.size()) {
                                productDoListSuccess.clear();
                                productDoListFailed.clear();
                                packageDetail = new OrderOutputPackageAddReq();
                                List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                                packageDetail.setProductList(productAddList1);
                                OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                                BeanUtils.copyProperties(res, addReq1);
                                packageAddReqList1.add(packageDetail);
                                if (storageId != 0) {
                                    addReq1.setStorageId(storageId);
                                    addReq1.setPackageList(packageAddReqList1);
                                    resList.add(addReq1);
                                    break kk;
                                }
                            } else {
                                productDoListSuccess.clear();
                                productAddList1.clear();
                                productDoListFailed.addAll(failedItems);
                                continue kk;
                            }
                        }
                    } else {
                        productDoListFailed.addAll(failedItems);
                    }
                    List<OrderOutputProductAddReq> productAddList2 = new ArrayList<>();
                    //所有捆包仓库无库存的产品
                    if (productDoListFailed.size() > 0) {//捆包仓库无库存，分别发
                        LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
                        queryWrapper.eq(StorageDo::getCountryType, 1);
                        List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
                        for (OrderOutputProductAddReq productDo : productDoListFailed) {
                            storageId = 0L;
                            shipPirce = 99999D;
                            Long productId = productDo.getProductId();
                            int count = productDo.getCount();
                            for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                                LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                                size = shipPriceService.countSameSkuSize(new double[4], productId, 1);
                                // wrapper2.eq(StockRecordDo::getShopId, res.getShopId()).eq(StockRecordDo::getProductInfoId, productId).eq(StockRecordDo::getStorageId, storageDo.getId());
                                // StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                                // int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId()) + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageDo.getId());
                                int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageDo.getId(), productId, count);
                                if (canUseCount >= count) {
                                    List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(), size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                    if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                    if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                        shipPirce = shipPriceDos.get(0).getPrice();
                                        storageId = storageDo.getId();
                                    }
                                }
                            }
                            if (storageId != 0) {
                                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                productAddList2 = new ArrayList<>();
                                productDetail.setProductId(productId);
                                productDetail.setCount(count);
                                productAddList2.add(productDetail);
                                packageDetail = new OrderOutputPackageAddReq();
                                packageAddReqList = new ArrayList<>();
                                packageDetail.setProductList(productAddList2);
                                addReq = new OrderOutputAddReq();
                                BeanUtils.copyProperties(res, addReq);
                                packageAddReqList.add(packageDetail);
                                addReq.setStorageId(storageId);
                                addReq.setPackageList(packageAddReqList);
//                                if (orderCount > 0) addReq.setOrderNo(addReq.getOrderNo() + "-" + orderCount);
//                                orderCount++;
                                resList.add(addReq);
                            } else {
                                //剩余SKU都没有库存
                                throw new BizExceptionI18(SysConstant.ORDER_NO_STOCK_ID, orderYahooDo.getOrderId(), failedItems.get(0).getCommoditySku());
//                                throw new BizException(String.format("%s(%s库存不足)", orderYahooDo.getOrderId(), failedItems.get(0).getCommoditySku()));
                            }
                        }
                    }
                }
            }
        }
        if (resList.size() > 0) {
            operateRecordService.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderYahooDo.getId(), currentUserId, 5);

//            operateRecord("点击发货", orderYahooDo.getId(), currentUserId);
        }
        return resList;
    }

    private String getAddress(String shipAddress1, String shipAddress2) {
        String address = shipAddress1;
        if (shipAddress1 == null) {
            address = shipAddress2;
        } else if (shipAddress2 == null) {
            address = shipAddress1;
        } else {
            address = shipAddress1 + shipAddress2;
        }
        return address;
    }

    @Override
    public SingleResult queryOrder2SendOutNoPackage(String orderid, Long userId, boolean b, Long companyId) {
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        OrderYahooDo orderYahooDo = this.baseMapper.selectById(orderid);
        List<String> failOrders = new ArrayList<>();
        if (orderYahooDo == null) throw new BizExceptionI18(SysConstant.NO_ORDER_INFO_ID, orderYahooDo.getOrderId());
//        if ("1".equals(orderYahooDo.getOrderStatus())||"2".equals(orderYahooDo.getOrderStatus()))
//            throw new BizException("该订单不在发货状态" + orderYahooDo.getOrderId());
        LambdaQueryWrapper<OrderYahooItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderYahooItemDo::getOrderId, orderid);
        List<OrderYahooItemDo> itemsDoList1 = itemDao.selectList(wrapper);
        List<OrderOutputProductAddReq> itemAddReqList = new ArrayList<>();

        //处理原产品信息   + ，组合产品情况
        for (OrderYahooItemDo productDo : itemsDoList1) {
            String itemId = StringUtils.isNotBlank(productDo.getSubCode()) ? productDo.getSubCode() : productDo.getItemId();
            if (itemId.contains("+")) {
                for (String sku : itemId.split("\\+")) {
                    OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                    Long productId = productInfoService.getProductId(sku, orderYahooDo.getCompanyId());
                    if (productId == null) {
                        failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), sku));
                        continue;
                    }
                    productDo1.setProductId(productId);
                    productDo1.setCommoditySku(sku);
                    productDo1.setCount(productDo.getQuantity());
                    itemAddReqList.add(productDo1);
                }
            } else {
                ProductInfoDo productInfoDo = productInfoService.getProductDo(itemId, orderYahooDo.getCompanyId());
                if (productInfoDo == null) {
                    failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_SKU_INFO2_ID, orderYahooDo.getOrderId(), itemId));
                    continue;
                }
                if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                    OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                    productDo1.setProductId(productInfoDo.getId());
                    productDo1.setCommoditySku(productInfoDo.getCommoditySku());
                    productDo1.setCount(productDo.getQuantity());
                    itemAddReqList.add(productDo1);
                } else {
                    LambdaQueryWrapper<ProductCombinationDo> productCombinationWrapper = new LambdaQueryWrapper<>();
                    productCombinationWrapper.eq(ProductCombinationDo::getParentId, productInfoDo.getId());
                    List<ProductCombinationDo> productCombinationDoList = productCombinationService.getBaseMapper().selectList(productCombinationWrapper);
                    for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                        if (productCombinationDo.getEffective() == 1) {
                            if (productCombinationDo.getEffectBeginTime() == null || productCombinationDo.getEffectEndTime() == null)
                                continue;
                            if (orderYahooDo.getOrderTime().getTime() < productCombinationDo.getEffectBeginTime().getTime()
                                    || orderYahooDo.getOrderTime().getTime() > productCombinationDo.getEffectEndTime().getTime())
                                continue;
                        }
                        OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                        ProductInfoDo productInfoDo1 = productInfoService.getById(productCombinationDo.getChildId());
                        if (productInfoDo1 == null) {
                            failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_SKU_GROUP_INFO_ID, orderYahooDo.getOrderId(), itemId));
                            continue;
                        }
                        productDo1.setProductId(productCombinationDo.getChildId());
                        productDo1.setCommoditySku(productInfoDo1.getCommoditySku());
                        productDo1.setCount(productDo.getQuantity() * productCombinationDo.getCount());
                        itemAddReqList.add(productDo1);
                    }
                }
            }
        }
        //订单
        OrderOutputAddReq res = new OrderOutputAddReq();
        if (orderYahooDo.getCompanyId() == 221) {
            if (orderYahooDo.getShipMethod().equals("postage5"))
                res.setTrackId(DicBusinessItemConstant.xinongExpress);
        }
        res.setSendDate(new Date());
        res.setPlatform("yahoo");
        res.setPlatformNumber(orderYahooDo.getId() + "");
        res.setShopId(orderYahooDo.getShopId());
        res.setCompanyId(orderYahooDo.getCompanyId());
        res.setOrderNo(orderYahooDo.getOrderId());
        res.setReceiverName(orderYahooDo.getShipLastName() + " " + orderYahooDo.getShipFirstName());
        res.setTelPhone(orderYahooDo.getShipPhoneNumber());
        res.setPostCode(orderYahooDo.getShipZipCode());
        res.setArea(orderYahooDo.getShipPrefecture());
        if (StringUtils.isNotBlank(orderYahooDo.getShipCity())) {
            res.setAddress(orderYahooDo.getShipCity() + getAddress(orderYahooDo.getShipAddress1(), orderYahooDo.getShipAddress2()));
        } else {
            res.setAddress(getAddress(orderYahooDo.getShipAddress1(), orderYahooDo.getShipAddress2()));
        }
        if (orderYahooDo.getShipRequestDate() != null) {
            res.setDeliveryDate(TimeUtils.formatDate(orderYahooDo.getShipRequestDate()));
        }
        if (orderYahooDo.getShipRequestTime() != null) {
            res.setDeliveryTime(orderYahooDo.getShipRequestTime().replaceAll(":00", ""));
        }

        //item
        List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
        LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
        List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
        for (OrderOutputProductAddReq productDo :
                itemAddReqList) {
            long storageId = 0L;
            long stateId = 0;
            double shipPirce = 99999D;
            int count = productDo.getCount();
            Long productId = productInfoService.getProductId(productDo.getCommoditySku(), res.getCompanyId());
            for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                double[] size = shipPriceService.countSameSkuSize(new double[4], productId,
                        1);
                // wrapper2.eq(StockRecordDo::getShopId, res.getShopId())
                //         .eq(StockRecordDo::getProductInfoId, productId)
                //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                // StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                // int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId())
                //         + stockDao.getOrderOutTurn2FbaCoun
                //         t(productId, res.getShopId(), storageDo.getId());
                int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageDo.getId(), productId, count);

                if (canUseCount >= count) {
                    List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                            size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                    if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                    if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                        shipPirce = shipPriceDos.get(0).getPrice();
                        storageId = storageDo.getId();
                    }
                }
            }
            if (storageId != 0) {
                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                productDetail.setProductId(productId);
                productDetail.setCount(count);
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                productAddList.add(productDetail);
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(productAddList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                addReq.setCod(0);
                packageAddReqList.add(packageDetail);
                if (storageId != 0) {
                    addReq.setStorageId(storageId);
                    addReq.setPackageList(packageAddReqList);
                    orderOutputAddReqList.add(addReq);
                }
            } else {
                //剩余SKU都没有库存
                failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_STOCK_ID, orderYahooDo.getOrderId(), productDo.getCommoditySku()));
            }

        }

        if (orderOutputAddReqList.size() > 0) {
            // operateRecordService.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderYahooDo.getId(), userId, 5);
        }
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoService.getById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> resList, Long userId, Long companyId) {
        List<String> failOrders = new ArrayList<>();
        failOrders.addAll(orderOutputService.addYahooList(resList, userId));
        if (failOrders.size() > 0) {
            return SingleResult.failure("300", SysConstant.EXPORT_OUT_ORDER_SUCCESS_ID, failOrders, resList.size() - failOrders.size());
        } else {
            return SingleResult.success(failOrders);
        }
    }


    @Override
    public int setOrderSend(Long[] orderids, Long userId) {
        int count = baseMapper.updateOrderSend(orderids);
        for (Long orderid : orderids) {
            operateRecordService.operateAddRecord(SysConstant.OPERATE_MARK_SEND, orderid, userId, 5);
        }
        return count;
    }

//    private void operateRecord(String str, Long orderRakutenId, Long userId) {
//        OperateRecordDo operateRecordDo = new OperateRecordDo();
//        operateRecordDo.setDeleteFlag(0);
//        operateRecordDo.setThirdId(orderRakutenId);
//        operateRecordDo.setType(5);
//        operateRecordDo.setOperateBy(userId);
//        operateRecordDo.setOperateTime(new Date());
//        operateRecordDo.setContent(str);
//        operateRecordDao.insert(operateRecordDo);
//    }


    @Override
    public boolean setOrderSysTips(Long orderId, String desc, Long companyId) {
        OrderYahooDo orderYahooDo = dao.selectById(orderId);
        orderYahooDo.setSystemMemo(desc);
        updateById(orderYahooDo);
        return true;
    }

    @Override
    public void syncYahooOrder(Map<String, String> map, int count) {
        String type = map.get("type");
        Long shopId = Long.parseLong(map.get("shopId"));
        String shopName = map.get("shopName");
        try {
            this.getYahooOrderList(shopId, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * yahoo 获取订单列表 日期传中国时间， 内部转成日本时间
     *
     * @param shopId
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> getYahooOrderList(Long shopId, Map<String, String> map) {
        String from = map.get("orderTimeFrom");
        String to = map.get("orderTimeTo");

        Date orderDateTo = StringUtils.isBlank(to) ? new Date() : DateUtils.stringFormatToDate(to, "yyyy-MM-dd HH:mm:ss");
        Date orderDateFrom = StringUtils.isBlank(from) ? DateUtils.passingDate(orderDateTo, -3) : DateUtils.stringFormatToDate(to, "yyyy-MM-dd HH:mm:ss");

//        orderDateTo = TimeUtils.formatDateToDate(orderDateTo, "yyyy-MM-dd HH:mm:ss", "Asia/Tokyo");//转成日本时间
//        orderDateFrom = TimeUtils.formatDateToDate(orderDateFrom, "yyyy-MM-dd HH:mm:ss", "Asia/Tokyo");//转成日本时间

        Map<String, Object> result = new HashMap<>();

        ShopDo shopDo = shopDao.selectById(shopId);
        if (shopDo == null || StringUtils.isBlank(shopDo.getYahooSellerId())) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo店铺没有sellerId");
            return result;
        }
        //todo 参数格式是 xml格式
        String field = "OrderId,Version,OriginalOrderId,ParentOrderId,DeviceType,IsSeen,IsSplit,IsRoyalty," + "RoyaltyFixTime,IsSeller,IsRatingB2s,OrderTime,ReleaseDate,LastUpdateTime,Suspect,OrderStatus," + "StoreStatus,PayStatus,SettleStatus,PayType,PayMethod,PayMethodName,PayDate,SettleId,BillFirstName," + "BillLastName,BillPrefecture,ShipStatus,ShipMethod,ShipMethodName,ShipRequestDate,ShipRequestTime,ShipNotes" + "ShipCompanyCode,ReceiveShopCode,ShipInvoiceNumber1,ShipInvoiceNumber2,ShipInvoiceNumberEmptyReason,ShipUrl," + "ArriveType,ShipDate,ShipFirstName,ShipLastName,ShipPrefecture,PayCharge,PayCharge,GiftWrapCharge," + "Discount,UsePoint,TotalPrice,RefundTotalPrice,sellerId,PayNo,ArrivalDate,printBillFlag";///Req/Search/Field

        int Result = 2000;   ///Req/Search/Result
        int Start = 1;       ///Req/Search/Start
        String Sort = "+order_time";///Req/Search/Sort
        String sellerId = shopDo.getYahooSellerId();///Req/SellerId
        //还有一个/Req/Search/Condition/

        //* 1需要 OrderID 或 OrderTime YYYYMMDDHH24MISS。
        //* 2如果未指定 OrderID，则需要 OrderTime、OrderTimeFrom、OrderTimeTo、PublicationTimeFrom 和 PublicationTimeTo 之一。
        //* 3指定以逗号分隔的多个匹配项。


        int total = 0;

        Set<String> orderIdList = new TreeSet<>();
        do {
            String body = null;
            //拼接参数 并且 转成日本时间
            String xmlParam = this.getYahooOrderListParam(Result, Start, orderDateFrom, orderDateTo, map.get("orderId"), field, sellerId);
            try {
                body = YahooUtils.yahooDoPost("https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/orderList", userService.getYahooUserAccessToken(shopId), xmlParam);
                Start += Result;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(body)) {
                result.put("code", "FAIL");
                result.put("msg", "连接超时");
                return result;
            }

            //<?xml version='1.0' encoding='UTF-8' ?>
            //<Error>
            //<Message>AccessToken has been expired. This API session is shorter than another API.</Message>
            //<Code>px-04102</Code>
            //</Error>

            List<OrderYahooEntity> list = null;
            try {
                JSONObject object = XmlUtils.xml2Json(body);
                if (object == null) {
                    result.put("code", "FAIL");
                    result.put("msg", "Yahoo 获取订单列表 xml格式解析空指针");
                    return result;
                } else if (StringUtils.isNotBlank(object.getString("Error"))) {
                    result.put("code", "FAIL");
                    result.put("msg", object.getJSONObject("Error").getString("Message"));
                    return result;
                } else {
                    total = object.getJSONObject("Result").getJSONArray("Search").getJSONObject(0).getInteger("TotalCount");
                    list = JSONArray.parseArray(object.getJSONObject("Result").getJSONArray("Search").getJSONObject(0).getString("OrderInfo"), OrderYahooEntity.class);
                }

            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (list == null) {
                result.put("code", "FAIL");
                result.put("msg", "Yahoo 获取订单列表 xml格式解析 数组null");
                return result;
            }
            ///Result/Error/Message
//            List<OrderYahooEntity> list = JSONArray.parseArray(body, OrderYahooEntity.class);
            for (OrderYahooEntity entity : list) {
                orderIdList.add(entity.getOrderId());
                OrderYahooDo et = dao.selectOne(new LambdaQueryWrapper<OrderYahooDo>().eq(OrderYahooDo::getOrderId, entity.getOrderId()).last(" order by id desc limit 1"));
                if (et == null) {
                    et = new OrderYahooDo();
                }

                BeanUtils.copyProperties(entity, et);
                et.setShopId(shopId);
                et.setOrderTime(DateUtils.stringFormatToDate(entity.getOrderTime(), "yyyy-MM-dd'T'hh:mm:ss"));
                et.setLastUpdateTime(DateUtils.stringFormatToDate(entity.getLastUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
                et.setShipRequestDate(DateUtils.stringFormatToDate(entity.getShipRequestDate()));
                et.setShipDate(DateUtils.stringFormatToDate(entity.getShipDate()));
                et.setArrivalDate(DateUtils.stringFormatToDate(entity.getArrivalDate()));
                et.setRoyaltyFixTime(DateUtils.stringFormatToDate(entity.getRoyaltyFixTime(), "yyyy-MM-dd'T'HH:mm:ss"));


                if (et.getId() == null) {
                    dao.insert(et);
                } else {
                    dao.updateById(et);
                }

            }
        } while (total > Result);

        //所有未完成的订单加入
        List<String> unFinshOrderIdList = dao.selectList(new LambdaQueryWrapper<OrderYahooDo>().ne(OrderYahooDo::getOrderStatus, 4).ne(OrderYahooDo::getOrderStatus, 5)).stream().map(OrderYahooDo::getOrderId).collect(Collectors.toList());
        orderIdList.addAll(unFinshOrderIdList);
        for (String orderId : orderIdList) {
            Map consumerMap = new HashMap();
            consumerMap.put("shopId", shopId);
            consumerMap.put("orderId", orderId);
            consumerMap.put("shopName", shopDo.getShopName());
            rabbitTemplate.convertAndSend("yahoo.getYahooOrderInfo", JSON.toJSONString(consumerMap));
        }
        result.put("code", "SUCCESS");
        return result;
    }


    public String getYahooOrderInfoParam(String orderId, String field, String sellerId) {
        StringBuilder builder = new StringBuilder("<Req><Target><OrderId>");
        builder.append(orderId).append("</OrderId>").append("<Field>").append(field).append("</Field>").append("</Target>").append("SellerId").append(sellerId).append("</SellerId>").append("</Req>");
        return builder.toString();
    }

    @Override
    public Map<String, Object> getYahooOrderInfo(Long shopId, String orderId) {
        Map<String, Object> result = new HashMap<>();
        ShopDo shopDo = shopDao.selectById(shopId);
        if (shopDo == null || StringUtils.isBlank(shopDo.getYahooSellerId())) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo店铺没有sellerId");
            return result;
        }

        OrderYahooDo et = dao.selectOne(new LambdaQueryWrapper<OrderYahooDo>().eq(OrderYahooDo::getOrderId, orderId).last("order by id desc limit 1"));
        if (et == null) {
            result.put("code", "FAIL");
            result.put("msg", "未匹配到订单");
            return result;
        }

        //参数 /Req/Target/OrderId /Req/Target/Field /Req/SellerId
        String field = "OrderId,Version,ChildOrderId,MobileCarrierName,CancelReason,CancelReasonDetail,IsRoyaltyFix,SuspectMessage," + "SendConfirmTime,SendPayTime,BuyerComments,SellerComments,Notes,OperationUser,Referer,EntryPoint,UsageId," + "UseCouponData,TotalCouponDiscount,ShippingCouponFlg,ShippingCouponDiscount,CampaignPoints,IsMultiShip," + "MultiShipId,IsFirstClassDrugIncludes,IsFirstClassDrugAgreement,IsWelcomeGiftIncludes,PayKind," + "SellerHandlingCharge,PayActionTime,PayNotes,ShipZipCode,ShipCity,ShipAddress1,ShipAddress2,ShipPhoneNumber," + "ShipEmgPhoneNumber,Adjustments,SettleAmount,GiftCardDiscount,SettlePayAmount,LineId,ItemId,Title,SubCode," + "ImageId,ProductId,CategoryId,UnitPrice,Quantity,CouponData,CouponDiscount,OriginalPrice,OriginalNum";

        String body = null;
        try {
            body = YahooUtils.yahooDoPost("https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/orderInfo", userService.getYahooUserAccessToken(shopId), getYahooOrderInfoParam(orderId, field, shopDo.getYahooSellerId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //<?xml version='1.0' encoding='UTF-8' ?>
        //<Error>
        //<Message>AccessToken has been expired. This API session is shorter than another API.</Message>
        //<Code>px-04102</Code>
        //</Error>

        if (StringUtils.isBlank(body)) {
            result.put("code", "FAIL");
            result.put("msg", "连接超时");
            return result;
        }
        OrderYahooDetailEntity entity = null;
        try {
            JSONObject object = XmlUtils.xml2Json(body);
            if (object == null) {
                result.put("code", "FAIL");
                result.put("msg", "Yahoo 获取订单详情 xml格式解析空指针");
                return result;
            } else if (StringUtils.isNotBlank(object.getString("Error"))) {
                result.put("code", "FAIL");
                result.put("msg", object.getJSONObject("Error").getString("Message"));
                return result;
            } else {
                String status = object.getJSONObject("ResultSet ").getJSONObject("Result").getString("Status");
                if ("OK".equals(status)) {
                    JSONArray array = object.getJSONObject("ResultSet ").getJSONObject("Result").getJSONArray("OrderInfo");
                    if (array.size() > 0) {
                        entity = array.getObject(0, OrderYahooDetailEntity.class);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        if (entity == null) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo 获取订单info xml格式解析 对象null");
            return result;
        }


        BeanUtils.copyProperties(entity, et);//todo 验证 item 是不是一对多

        et.setPayKind(entity.getPay().get(0).getPayKind());
        et.setSellerHandlingCharge(entity.getPay().get(0).getSellerHandlingCharge());
        et.setPayActionTime(DateUtils.stringFormatToDate(entity.getPay().get(0).getPayActionTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        et.setPayNotes(entity.getPay().get(0).getPayNotes());
        et.setShipZipCode(entity.getShip().get(0).getShipZipCode());
        et.setShipCity(entity.getShip().get(0).getShipCity());
        et.setShipAddress2(entity.getShip().get(0).getShipAddress2());
        et.setShipAddress1(entity.getShip().get(0).getShipAddress1());
        et.setShipPhoneNumber(entity.getShip().get(0).getShipPhoneNumber());
        et.setShipEmgPhoneNumber(entity.getShip().get(0).getShipEmgPhoneNumber());
        et.setAdjustments(entity.getDetail().get(0).getAdjustments());
        et.setSettleAmount(entity.getDetail().get(0).getSettleAmount());
        et.setGiftCardDiscount(entity.getDetail().get(0).getGiftCardDiscount());
        et.setSettlePayAmount(entity.getDetail().get(0).getSettlePayAmount());
        et.setCouponData(entity.getItem().get(0).getCouponData());
        et.setCouponDiscount(entity.getItem().get(0).getCouponDiscount());
        et.setOriginalPrice(entity.getItem().get(0).getOriginalPrice());
        et.setOriginalNum(entity.getItem().get(0).getOriginalNum());
        dao.updateById(et);
        result.put("code", "SUCCESS");
        return result;
    }

    public Map<String, Object> orderShipStatusChange(OrderShipStatusChangeReq req) {
        Map<String, Object> result = new HashMap<>();
        ShopDo shopDo = shopDao.selectById(req.getShopId());
        if (shopDo == null || StringUtils.isBlank(shopDo.getYahooSellerId())) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo店铺没有sellerId");
            return result;
        }


        StringBuilder builder = new StringBuilder("<Req><Target><OrderId>");
        builder.append(req.getOrderId()).append("</OrderId>").append("<IsPointFix>").append(req.getIsPointFix()).append("</IsPointFix>");
        if (StringUtils.isNotBlank(req.getOperationUser())) {
            builder.append("<OperationUser>").append(req.getOperationUser()).append("</OperationUser>");
        }
        builder.append("</Target><Order>").append("<Ship><ShipStatus>").append(req.getShipStatus()).append("</ShipStatus>");
        if (StringUtils.isNotBlank(req.getShipMethod())) {
            builder.append("<ShipMethod>").append(req.getShipMethod()).append("</ShipMethod>");
        }
        if (StringUtils.isNotBlank(req.getShipNotes())) {
            builder.append("<ShipNotes>").append(req.getShipNotes()).append("</ShipNotes>");
        }
        if (StringUtils.isNotBlank(req.getShipCompanyCode())) {
            builder.append("<ShipCompanyCode>").append(req.getShipCompanyCode()).append("</ShipCompanyCode>");
        }
        if (StringUtils.isNotBlank(req.getShipInvoiceNumber1())) {
            builder.append("<ShipInvoiceNumber1>").append(req.getShipInvoiceNumber1()).append("</ShipInvoiceNumber1>");
        }
        if (StringUtils.isNotBlank(req.getShipInvoiceNumber2())) {
            builder.append("<ShipInvoiceNumber2>").append(req.getShipInvoiceNumber2()).append("</ShipInvoiceNumber2>");
        }
        if (StringUtils.isNotBlank(req.getShipUrl())) {
            builder.append("<ShipUrl><![CDATA[").append(req.getShipUrl()).append("]]></ShipUrl>");
        }
        if (StringUtils.isNotBlank(req.getShipDate())) {
            builder.append("<ShipDate>").append(req.getShipDate()).append("</ShipDate>");
        }
        if (StringUtils.isNotBlank(req.getArrivalDate())) {
            builder.append("<ArrivalDate>").append(req.getArrivalDate()).append("</ArrivalDate>");
        }
        builder.append("</Ship></Order><SellerId>").append(shopDo.getYahooSellerId()).append("</SellerId></Req>");

        String body = null;
        try {
            body = YahooUtils.yahooDoPost("https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/orderShipStatusChange", userService.getYahooUserAccessToken(req.getShopId()), builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(body)) {
            result.put("code", "FAIL");
            result.put("msg", "连接超时");
            return result;
        }

        JSONObject object = null;
        try {
            object = XmlUtils.xml2Json(body);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (object == null) {
            result.put("code", "FAIL");
            result.put("msg", "Yahoo 获取订单详情 xml格式解析空指针");
        } else if (StringUtils.isNotBlank(object.getString("Error"))) {
            result.put("code", "FAIL");
            result.put("msg", object.getJSONObject("Error").getString("Message"));
        } else {
            String status = object.getJSONObject("ResultSet ").getJSONObject("Result").getString("Status");
            if ("OK".equals(status)) {
                result.put("code", "SUCCESS");
            } else {
                result.put("code", "FAIL");
                result.put("msg", "发货失败");
            }
        }

        //<!-- •サンプルXML-->
        //
        //<ResultSet totalResultsAvailable="1" totalResultsReturned="1" ok="1" ng="0">
        //    <Result>
        //        <Status>OK</Status>
        //    </Result>
        //</ResultSet>
        //
        //
        //<!-- •警告ありのサンプルXML-->
        //
        //<ResultSet totalResultsAvailable="1" totalResultsReturned="1" ok="1" ng="0">
        //    <Result>
        //        <Status>OK</Status>
        //        <Warning>
        //            <Code>od91113</Code>
        //            <Message></Message>
        //            <Detail></Detail>
        //        </Warning>
        //    </Result>
        //</ResultSet>
        ///Error	-	エラーレスポンスのすべてを含みます。
        ///Error/Code	string	エラーコード
        ///Error/Message	string	エラーメッセージ
        ///Error/Detail	-	エラー詳細（ある場合）
        ///Error/Detail/SettleCode	string	決済システムのエラーコード（APIエラーコードが「od91112」の場合）
        return result;
    }

    @Override
    public void autoSendYahooOrder() {
        List<Long> companyIds = new ArrayList<>();
        companyIds.add(636L);
        companyIds.add(404L);
        for (Long companyId : companyIds) {
            List<OrderYahooDo> orderRakutenDos = dao.selectList(new LambdaQueryWrapper<OrderYahooDo>()
                    .eq(OrderYahooDo::getShipStatus, 1)
                    .eq(OrderYahooDo::getPayStatus, 1)
                    .eq(OrderYahooDo::getIsSendOut, 0)
                    .ge(OrderYahooDo::getOrderTime, TimeUtils.getCurrentDateFormat(-30))
                    .eq(OrderYahooDo::getCompanyId, companyId));
            if (orderRakutenDos.isEmpty()) continue;
            List<String> collect = orderRakutenDos.stream().map(rakutenDo -> rakutenDo.getId() + "").collect(Collectors.toList());
            if (collect.isEmpty()) continue;
            queryOrder2SendOut(collect.toArray(new String[collect.size()]), 1L, true, companyId);

        }
    }

    @Override
    public void exportExcel(OrderYahooQueryBo bo, HttpServletResponse response) throws IOException {
        List<OrderYahooDo> OrderYahooDoList;
        if (CollectionUtils.isEmpty(bo.getIds())) {
            LambdaQueryWrapper<OrderYahooDo> wrapper = queryBuild(bo);
            OrderYahooDoList = this.baseMapper.selectList(wrapper);
        } else {
            LambdaQueryWrapper<OrderYahooDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(OrderYahooDo::getId, bo.getIds())
                    .eq(Objects.nonNull(bo.getCompanyId()), OrderYahooDo::getCompanyId, bo.getCompanyId())
                    .orderByDesc(OrderYahooDo::getCreateTime);
            OrderYahooDoList = this.baseMapper.selectList(wrapper);
        }
        if (OrderYahooDoList.size() > 1000) {
            response.setStatus(500);
            throw new BizExceptionI18(SysConstant.Order_Count_Oversize_1000);
        }
        List<OrderYahooExcelExportVo> excelExportVoList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(OrderYahooDoList)) {
            for (OrderYahooDo rakutenDo : OrderYahooDoList) {
                OrderYahooExcelExportVo excelExportVo = new OrderYahooExcelExportVo();
                BeanUtils.copyProperties(rakutenDo, excelExportVo);

                LambdaQueryWrapper<OrderYahooItemDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                packageDoLambdaQueryWrapper.eq(OrderYahooItemDo::getOrderId, rakutenDo.getId());
                List<OrderYahooItemDo> productDoList = itemDao.selectList(packageDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(productDoList)) {
                    List<OrderYahooItemExcelExportVo> productExcelExportVoList = new ArrayList<>();
                    for (OrderYahooItemDo productDo : productDoList) {
                        OrderYahooItemExcelExportVo productExcelExportVo = new OrderYahooItemExcelExportVo();
                        BeanUtils.copyProperties(productDo, productExcelExportVo);
                        productExcelExportVoList.add(productExcelExportVo);
                    }
                    excelExportVo.setItems(productExcelExportVoList);
                }
                excelExportVoList.add(excelExportVo);
            }
        }
        ExportParams exportParams = new ExportParams();
        exportParams.setCreateHeadRows(true);
        exportParams.setHeaderColor(IndexedColors.YELLOW.getIndex());
        ExcelUtils.exportExcel(excelExportVoList, OrderYahooExcelExportVo.class, "yahoo订单", exportParams, response);
    }
}
